<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 搜索添加 -->
      <el-row :gutter="20">
        <el-col :span="10">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUsers">
            <el-button slot="append" icon="el-icon-search" @click="getUsers"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表明细 -->
      <el-table :data="userList" border strip>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch @change="stateChange(scope.row)" v-model="scope.row.mg_state" active-color="#13ce66"
              inactive-color="#cccccc"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="260px">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="modify(scope.row.id)">修改</el-button>
            <el-button type="danger" size="mini" @click="del(scope.row.id)">删除</el-button>
            <el-tooltip effect="dark" content="分配角色" placement="top" enterable>
              <el-button type="warning" size="mini" @click="setRole(scope.row)">权限</el-button>
            </el-tooltip>
          </template>>
        </el-table-column>
      </el-table>
      <!-- 分页页面 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page.sync="queryInfo.pagenum" :page-sizes="[1, 2, 5, 10]" :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-card>
    <!-- 添加用户页面 -->
    <el-dialog title="提示" :visible.sync="addVisible" width="50%" @close="ifClose">
      <!-- 主题内容 -->
      <!-- <span>确定要进行更改吗?</span> -->
      <el-form :model="ruleForm" :rules="rules" ref="ruleFormRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="ruleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="ruleForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="ruleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="ruleForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户页面 -->
    <el-dialog title="修改用户信息" :visible.sync="editVisible" width="50%">
      <el-form :model="editForm" :rules="rules" ref="editFormRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="editForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="editVisible = false">取消</el-button>
        <el-button type="primary" @click="editUser">确定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色的对话框 -->
    <el-dialog title="分配权限" :visible.sync="aaa" width="50%">
      <div>
        <p>当前用户:{{ userInfo.username }}</p>
        <br>
        <p>当前角色:{{ userInfo.role_name }}</p>
        <br>
        <p>分配角色: <el-select v-model="selectRole" placeholder="请选择">
            <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id">
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer">
        <el-button @click="aaa = false">取消</el-button>
        <el-button type="primary" @click="saveRole">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>



export default {
  name: 'WorkspaceJsonUsers',

  data () {
    //自定义验证邮箱的规则
    var checkEmail = (rule, value, callback) => {
      //正则表达式
      const regEmail = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
      if (regEmail.test(value)) {
        callback();
      } else {
        callback(new Error('请输入正确的邮箱地址'));
      }
    };
    //自定义验证手机号的规则
    var checkMobile = (rule, value, callback) => {
      //正则表达式
      const regMobile = /^1[3456789]\d{9}$/;
      if (regMobile.test(value)) {
        callback();
      } else {
        callback(new Error('请输入正确的手机号'));
      }
    };



    return {

      //获取用户列表数据
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2,
      },

      //用户列表数据
      userList: [],
      total: 0,
      addVisible: false,
      editVisible: false,
      userInfo: {

      },
      //所有角色数据列表
      roleList: [

      ],
      //分配权限对话框的显示与隐藏
      aaa: false,
      //已选中的角色id值
      selectRole: '',
      //添加用户的表单数据
      ruleForm: {
        username: '',
        password: '',
        email: '',
        mobile: '',



      },
      editForm: {
        username: '',
        password: '',
        email: '',
        mobile: '',

      },
      //添加表单验证规则对象
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 11, message: '长度在 5 到 11 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' },
        ],

      },

    };
  },
  created () {
    this.getUsers();

  },

  mounted () {

  },

  methods: {
    async getUsers () {
      await this.$http.get('users', { params: this.queryInfo }).then(res => {
        if (res.data.meta.status !== 200)
          return this.$message.error('获取用户列表失败');
        // console.log(res.data.data.users);
        this.userList = res.data.data.users;
        this.total = res.data.data.total;
      })
    },
    // 监听页码改变
    handleSizeChange (newsize) {
      this.queryInfo.pagesize = newsize;
      this.getUsers();
    },
    handleCurrentChange (newPage) {
      this.queryInfo.pagenum = newPage;
      this.getUsers();
    },
    // 监听开关按钮改变
    stateChange (state) {
      console.log(state);
      this.$http.put(`users/${state.id}/state/${state.mg_state}`).then(res => {
        if (res.data.meta.status !== 200)
          return this.$message.error('修改用户状态失败');
        this.$message.success('修改用户状态成功');
      })
      //users/:uId/state/:type
    },
    //监听添加对话框的关闭事件
    ifClose () {
      this.$refs.ruleFormRef.resetFields();
    },
    //添加用户
    addUser () {
      this.$refs.ruleFormRef.validate(async valid => {
        if (!valid) return;
        await this.$http.post('users', this.ruleForm).then(res => {
          if (res.data.meta.status !== 201)
            return this.$message.error('添加用户失败');
          this.$message.success('添加用户成功');
          this.getUsers();
          this.addVisible = false;
        })
      })
    },
    // 修改用户
    modify (id) {

      // 根据id获取用户信息
      this.$http.get(`users/${id}`).then(res => {
        if (res.data.meta.status !== 200)
          return this.$message.error('获取用户信息失败');
        this.editForm = res.data.data;
      }, err => {
        console.log(err);
      }),
        this.editVisible = true;
    },
    // 监听修改对话框的关闭事件
    ifClose () {
      this.$refs.ruleFormRef.resetFields();
    },
    // 删除用户
    del (id) {
      this.$confirm('确认删除该用户吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await this.$http.delete(`users/${id}`).then(res => {
          if (res.data.meta.status !== 200)
            return this.$message.error('删除用户失败');
          this.$message.success('删除用户成功');
          this.getUsers();
        })
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    //修改用户并提交
    editUser () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return;
        await this.$http.put(`users/${this.editForm.id}`, this.editForm).then(res => {
          if (res.data.meta.status !== 200)
            return this.$message.error('修改用户失败');
          this.$message.success('修改用户成功');
          this.getUsers();
          this.editVisible = false;
        })
      })
    },
    //权限分配
    setRole (userInfo) {
      //把当前用户信息保存到userInfo中 
      this.userInfo = userInfo;
      //获取所有角色列表
      this.$http.get('roles').then(res => {
        if (res.data.meta.status !== 200)
          return this.$message.error('获取角色列表失败');
        this.roleList = res.data.data;
        // console.log(this.roleList);
      })
      this.aaa = true;

    },
    //分配用户角色
  async  saveRole () {
      if (this.selectRole === '') {
        return this.$message.error('请选择分配角色');
      }
       this.$http.put(`users/${this.userInfo.id}/role`, { rid: this.selectRole }).then(res => {
        if (res.data.meta.status !== 200)
          return this.$message.error('分配角色失败');
        this.$message.success('分配角色成功');
        this.getUsers();
        this.aaa = false;
      })
    }








  },
};
</script>

<style lang="less" scoped></style>